﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Threading;
using System.Collections;

namespace INSAForManagers
{
    public partial class FormResearch : Form
    {
        private FormACard formParent;
        private string fileName;
        private DataTable tbl;

        public FormResearch(FormACard parent)
        {
            InitializeComponent();
            this.formParent = parent;
            Control.CheckForIllegalCrossThreadCalls = false;
            tbl = new DataTable();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lnkXlsRead_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "엑셀 파일(*.xls) | *.xls";
            dlg.Multiselect = false;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                fileName = dlg.FileName;
                Thread t = new Thread(new ThreadStart(readXlsList));
                t.Start();
            }

            lnkSave.Enabled = false;
        }

        private void readXlsList()
        {
            try
            {
                clearDGV();

                Util.openXls(fileName);
                Util.changeSheet(5);

                Excel.Range range;

                range = Util.OSheet.get_Range("A4", "F30");

                object[,] val = (object[,])range.get_Value(Missing.Value);
                double totalPoint = 0.0;
                double maxValue = 0.0;//학위점수와 합산하여 3점 제한
                
                if (val[1, 1] != null)
                {
                    double tmpScholarPoint = DBUtil.getScholarPoint(formParent.txtPCode.Text);

                    if (tmpScholarPoint >= 1.0)
                    {
                        maxValue = 3.0 - tmpScholarPoint;
                    }
                    else
                    {
                        maxValue = 3.0;
                    }
                }
                for (int i = 1; i <= val.GetUpperBound(0); i++)
                {
                    if (val[i, 1] == null)
                    {
                        Util.closeXls();
                        return;
                    }

                    DataRow row = tbl.NewRow();
                    row[0] = val[i, 1].ToString().Trim();
                    row[1] = val[i, 2].ToString().Trim();
                    row[2] = DateTime.Parse(val[i, 3].ToString());
                    row[3] = val[i, 4].ToString().Trim();
                    row[4] = val[i, 5].ToString().Trim();
                    row[5] = val[i, 6].ToString().Trim();
                    row[6] = (double)Util.getResearchPoint(row[3].ToString(), row[4].ToString(), row[5].ToString());
                    double tmpValue = Double.Parse(row[6].ToString());
                    totalPoint += tmpValue;
                    if (totalPoint > maxValue)
                    {
                        row[6] = tmpValue - (totalPoint - maxValue) > 0 ? tmpValue - (totalPoint - maxValue) : 0.0;
                    }
                    
                    tbl.Rows.Add(row);
                }

                dgvResearchList.DataSource = tbl;

                Util.setBackColor(dgvResearchList, tbl.Rows.Count, Color.FromArgb(240, 240, 240));

                Util.closeXls();

                lnkSave.Enabled = false;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "확인");
                Util.closeXls();
            }
        }

        private void clearDGV()
        {
            tbl.Rows.Clear();
            dgvResearchList.DataSource = tbl;
        }

        private void FormCareer_Load(object sender, EventArgs e)
        {
            try
            {
                addColumns();

                initGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "확인");
            }
        }

        private void addColumns()
        {
            DataColumn col = null;

            //대회주관기관
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "대회주관기관";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //대회명
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "대회명";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //입상일자
            col = new DataColumn();
            col.DataType = Type.GetType("System.DateTime");
            col.ColumnName = "입상일자";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //규모
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "규모";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //등급
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "등급";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //참여인원
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "참여인원";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //평정점
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "평정점";
            col.AllowDBNull = false;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            dgvResearchList.DataSource = tbl;

            dgvResearchList.Columns[0].Width = 100;
            dgvResearchList.Columns[1].Width = 100;
            dgvResearchList.Columns[2].Width = 100;
            dgvResearchList.Columns[3].Width = 70;
            dgvResearchList.Columns[4].Width = 70;
            dgvResearchList.Columns[5].Width = 70;
            dgvResearchList.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvResearchList.Columns[6].Width = 70;
            dgvResearchList.Columns[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvResearchList.Columns[6].DefaultCellStyle.Format = "#0.0000";

        }

        private void initGrid()
        {
            string pcode = formParent.txtPCode.Text;
            if (pcode.Equals(""))
            {
                MessageBox.Show("대상자를 입력 후에 다시 시도하세요!   ", "확인");
                this.Close();
                return;
            }

            ArrayList list = DBUtil.getListFromResearchTable(pcode);
            for (int i = 0; i < list.Count; i++) 
            {

                ArrayList data = (ArrayList)list[i];

                DataRow row = tbl.NewRow();
                row[0] = data[2].ToString();
                row[1] = data[3].ToString();
                row[2] = DateTime.Parse(data[4].ToString());
                row[3] = data[5].ToString();
                row[4] = data[6].ToString();
                row[5] = data[7].ToString();
                row[6] = Double.Parse(data[8].ToString());

                tbl.Rows.Add(row);
            }

            dgvResearchList.DataSource = tbl;

            Util.setBackColor(dgvResearchList, tbl.Rows.Count, Color.FromArgb(240,240,240));
            
        }

        private void lnkCalcEvalue_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            double total_point = 0.0;
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                total_point += Double.Parse(tbl.Rows[i][6].ToString());
            }
            //학위취득점수와 연구점수의 합이 3.0을 초과하면 초과한 점수를 제거한 후 반영함
            double schPoint = double.Parse(formParent.txtScholarPoint.Text);
            if (total_point + schPoint > 3.0)
            {
                total_point = 3.0 - schPoint;
                if (total_point < 0) total_point = 0;
            }
            lblTotalPoint.Text = total_point.ToString("#0.0000");

            lnkSave.Enabled = true;
        }

        private void lnkSave_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                DBUtil.beginTans();
                DBUtil.deleteFromResearchTable(formParent.txtPCode.Text);
                for (int i = 0; i < tbl.Rows.Count; i++)
                {
                    ArrayList data = new ArrayList();
                    data.Add(formParent.txtPCode.Text);
                    data.Add(tbl.Rows[i][0].ToString());
                    data.Add(tbl.Rows[i][1].ToString());
                    data.Add(DateTime.Parse(tbl.Rows[i][2].ToString()));
                    data.Add(tbl.Rows[i][3].ToString());
                    data.Add(tbl.Rows[i][4].ToString());
                    data.Add(tbl.Rows[i][5].ToString());
                    data.Add(Double.Parse(tbl.Rows[i][6].ToString()));
                    data.Add(DateTime.Now);

                    DBUtil.insertResearchInfo(data);
                }
            }
            catch (Exception ex)
            {
                DBUtil.rollBack();
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            DBUtil.commit();
            MessageBox.Show("저장하였습니다.    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            string total_point = lblTotalPoint.Text;
            if (total_point.Equals("-"))
            {
                formParent.txtResearchPoint.Text = "0.0";
            }
            else
            {
                formParent.txtResearchPoint.Text = total_point;
            }
            this.Close();
        }

        private void FormResearch_Load(object sender, EventArgs e)
        {
            try
            {
                addColumns();

                initGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "확인");
            }
        }
    }
}
